#!/bin/bash

colorStr()
{
    if [ "$1" = 'red' ];then
        echo -e '\033[1;31m'$2'\033[0m'
        msgMattermost red "$2"
    elif [ "$1" = 'green' ];then
        echo -e '\033[1;32m'$2'\033[0m'
    elif [ "$1" = 'yellow' ];then
        echo -e '\033[33m'$2'\033[0m'
    elif [ "$1" = 'blue' ];then
        echo -e '\033[34m'$2'\033[0m'
    elif [ "$1" = 'bold' ];then
        echo -e '\033[1m'$2'\033[0m'
    fi
}

newline=$'\n'

msgMattermost()
{

   colorStr blue ">>> notice msgmattermost"

    # if [ "$1" = 'red' ];then
        # color="#FF3030"
    # elif [ "$1" = 'green' ];then
        # color="#43CD80"
    # elif [ "$1" = 'yellow' ];then
        # color="#EEEE00"
    # elif [ "$1" = 'blue' ];then
        # color="#87CEFF"
    # elif [ "$1" = 'bold' ];then
        # color="#8B7765"
    # fi


    # text=$(echo "$2" | sed 's/\\/\\\\/g' | sed 's/\"/\\"/g' | sed 's/&/ and /g' )

    # url='http://mattermost.gitlab.toc/hooks/eccwqe8w13dutk64msiiqphtua'

    # payload='payload={
        # "username":"Docker小女仆",
        # "text":"@'$GITLAB_USER_NAME'",
        # "attachments":[
            # {
            # "color":"'$color'",
            # "title":"'$CI_PROJECT_PATH_SLUG'",
            # "title_link":"'$CI_PROJECT_URL'/branches/",
            # "text":"'"$text"'"f
            # }
        # ]
    # }'

    # curl -X POST -d "$payload" "$url"
}

gitDir="git@gitlab.my:9122/backend"

pullBranch(){
    if [[ `git branch | grep $branch_release_name` ]]; then
        colorStr blue ">>> del branch $1"
        git branch -q -D $1
    fi
    colorStr blue ">>> checkout to ${1} and pull"
    git checkout -q $1
    git pull -q
}

pullTag(){
    if [ "$2" = 0 ];then
        colorStr blue ">>> del tag ${1} and pull"
        git tag -d $1
        git pull -q
    fi
    colorStr blue ">>> checkout to $1"
    git checkout -q $1
}

currentBranch(){
    # 获取当前分支
    git rev-parse --abbrev-ref HEAD
}

pullBackendProject()
{
    cd backend

    if [[ ! -d "$1" ]];then
        new=1
        git clone $gitDir/$1.git $1
        cd $1
    elif [[ ! -d "${1}/.git" ]];then
        new=1
        rm -rf $1
        git clone $gitDir/$1.git $1
        cd $1
    else
        new=0
        cd $1

        git reset HEAD .
        git checkout .
        $currentBranch=`currentBranch`
        if [ "$currentBranch" != "master" ];then
            colorStr blue '>>> checkout to master'
            git checkout master
        fi

        colorStr blue '>>> pull master and fetch -p'
        git pull
        git fetch -p

        branchNameArr=`git branch -vv | grep -E ': gone]|: 丢失]' | awk '{print $1}'`;
        if [[ -n "$branchNameArr" ]];then
            colorStr blue '>>> clean up overdue branchs'
            git branch -D $branchNameArr
        fi
    fi

    # 依次序检查release hotfix tag
    branch_release_name="release/$2"
    branch_hotfix_name="hotfix/$2"
    feature_branch_name="$2"
    tag_name="v$2"

    if [[ `git branch -r | grep $branch_release_name` ]]; then
        colorStr blue ">>> the branch $branch_release_name exists"
        pullBranch $branch_release_name
    elif [[ `git branch -r | grep $branch_hotfix_name` ]]; then
        colorStr blue ">>> the branch $branch_hotfix_name exists"
        pullBranch $branch_hotfix_name
	elif [[ `git branch -r | grep $feature_branch_name` ]]; then
        colorStr blue ">>> the branch $feature_branch_name exists"
        pullBranch $feature_branch_name
		
    elif [[ `git ls-remote -t | grep $tag_name` ]]; then
        colorStr blue ">>> the tag $tag_name already exists"
        pullTag $tag_name $new
	
    else
        colorStr red "项目 ${1} 的 ${2} hotfix|release分支或者tag都不存在"
        exit 1
    fi

    cd $CI_PROJECT_DIR
}

echo
colorStr green "定义全局变量"
DOCKER_HUB=127.0.0.1:50000/
PROJECT_NAME=${CI_PROJECT_PATH#*/}
PROJECT_NAME_AND_TAG=${PROJECT_NAME}:${CI_COMMIT_REF_NAME#*/}
IMAGE_NAME_AND_TAG=${CI_PROJECT_PATH_SLUG}:${CI_COMMIT_REF_NAME#*/}
PROJECT_REAL_PATH=/opt/wwwroot/toc/${PROJECT_NAME}

IMAGE_PUSH_PATH=${DOCKER_HUB}toc/${IMAGE_NAME_AND_TAG}

colorStr blue ">>> PROJECT_NAME_AND_TAG is ${PROJECT_NAME_AND_TAG}"
colorStr blue ">>> IMAGE_NAME_AND_TAG is ${IMAGE_NAME_AND_TAG}"
colorStr blue ">>> PROJECT_REAL_PATH is ${PROJECT_REAL_PATH}"
colorStr blue ">>> IMAGE_PUSH_PATH is ${IMAGE_PUSH_PATH}"

echo 
colorStr green "开始必要的验证和配置检查"

if [[ "$CI_PROJECT_NAMESPACE" != 'backend' && ! "$CI_PROJECT_NAMESPACE" =~ ^'backend/' ]];then
    colorStr red "${CI_PROJECT_NAMESPACE} 不是一个后端项目"
    exit 1
fi

master_last_commit=`git log -1 --oneline --no-merges remotes/origin/master`
log_list=`git log --oneline --no-merges ${master_last_commit%% *}.. | awk '{$1="1.";print $0}'`

if [ -z "$log_list" ];then
    self_last_commit=`git log -1 --oneline --no-merges`
    if [ "$master_last_commit" == "$self_last_commit" ];then
        colorStr red '没有更新，不需要推送'
        exit
    else
        colorStr red "未找到master最后一次提交${master_last_commit}，请先rebase master"
        exit 1
    fi
fi

if [[ ! "$CI_COMMIT_REF_NAME" =~ ^(hotfix|release)\/2[0-9][0-9]{6}$ ]];then
    colorStr red "项目名称 ${CI_COMMIT_REF_NAME} 不匹配 ^(hotfix|release)/20[0-9]{6}$ 规则"
    exit 1
fi

colorStr blue ">>> 验证通过"

echo
colorStr green "将当前目录复制到 ${CI_PROJECT_PATH}"
mkdir -p $CI_PROJECT_PATH